package com.diy.sigmund.diycommon.spring.config.dynamicthreadpool;

import java.util.Objects;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy;
import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;


/**
 * @author ylm-sigmund
 * @since 2023/1/29 22:36
 */
public enum RejectedExecutionHandlerEnum {
    /** AbortPolicy */
    ABORT_POLICY("AbortPolicy", new AbortPolicy()),
    /** CallerRunsPolicy */
    CALLER_RUNS_POLICY("CallerRunsPolicy", new CallerRunsPolicy()),
    /** DiscardOldestPolicy */
    DISCARD_OLDEST_POLICY("DiscardOldestPolicy", new DiscardOldestPolicy()),
    /** DiscardPolicy */
    DISCARD_POLICY("DiscardPolicy", new DiscardPolicy()),

    ;
    /** 拒绝策略类型 */
    private String rejectedExecutionType;
    /** 拒绝策略 */
    private RejectedExecutionHandler rejectedExecutionHandler;

    RejectedExecutionHandlerEnum(String rejectedExecutionType,
            RejectedExecutionHandler rejectedExecutionHandler) {
        this.rejectedExecutionType = rejectedExecutionType;
        this.rejectedExecutionHandler = rejectedExecutionHandler;
    }

    public String getRejectedExecutionType() {
        return rejectedExecutionType;
    }

    public RejectedExecutionHandler getRejectedExecutionHandler() {
        return rejectedExecutionHandler;
    }

    public static RejectedExecutionHandler getRejectedExecutionHandler(String rejectedExecutionType) {
        for (RejectedExecutionHandlerEnum value : RejectedExecutionHandlerEnum.values()) {
            if (Objects.equals(value.getRejectedExecutionType(), rejectedExecutionType)) {
                return value.getRejectedExecutionHandler();
            }
        }
        throw new IllegalArgumentException("code is not in this enum");
    }
}
